# Create your views here.
import datetime
import os
from xml.dom import minidom
from xml.parsers import expat as XmlException

from django.template import Context, loader
from django.http import HttpResponse

from settings import DIRS


#load global data
indicator_types = {"Actor Indicator": {"status": "active", "short_name": "Actor", "url": "/reflexion/actor"}, 
                  "Network Indicator": {"status": "inactive", "short_name": "Network", "url": "/reflexion/network"},
                  "All type Indicator": {"status": "inactive", "short_name": "All type", "url": "/reflexion/anytype"},
                  }

actor_indicators = {"Actor answers": {"status": "inactive", "url": "/reflexion/indicator/actor_answers"}, 
                    "Actor coordination": {"status": "inactive", "url": "/reflexion/indicator/actor_coordination"}}
network_indicators = {"Network answers": {"status": "inactive", "url": "/reflexion/indicator/network_answers"},
                      "Network coordination": {"status": "inactive", "url": "/reflexion/indicator/network_coordination"}, 
                      "Optional collaborative activity function": {"status": "inactive", "url": "/reflexion/indicator/network_optionalcaf"},
                      "Collaborative activity function": {"status": "inactive", "url": "/reflexion/indicator/network_caf"}, 
                      "Collaboration function": {"status": "inactive", "url": "/reflexion/indicator/network_cf"}}
all_indicators = {}
for key, value in actor_indicators.items():
    all_indicators[key] = value
for key, value in network_indicators.items():
    all_indicators[key] = value

indicator_selected = ""
welcome = "IASNA Project es sitio realizado para mostrar a los actores de una actividad " \
            "colaborativa los indicadores de colaboracion que se generaron usando metodos formales de SNA. " \
            "Seleccione la actividad realizada que quiera visualizar, luego el indicador y seguidamente " \
            "el tipo de analisis, de red o de actor."

modules = {"Iasna Core": {"status": "inactive", "short_name": "iasna", "url": "/iasna/"}, 
           "Iasna Teamquest": {"status": "inactive", "short_name": "teamquest", "url": DIRS["TEAMQUEST_URL"]},
           "Iasna Reflexion": {"status": "active", "short_name": "reflexion", "url": DIRS["REFLEXION_URL"]},
           "Iasna Recommendation": {"status": "inactive", "short_name": "recommendation", "url": DIRS["RECOMMENDATION_URL"]},
           }
TEMPLATES_MEDIA_URL = DIRS["PROJECT_MEDIA_URL"] + 'myTemplates/snow-flakes/'

#configurar active en grafico
def link_activated(list_links, key):
    for list_link in list_links:
        if list_link.lower().replace(" ", "_") == key.lower().replace(" ", "_"):
            list_links[list_link]["status"] = "active"
        else: list_links[list_link]["status"] = "inactive"
        
def link_to_visit(list_links, complement):
    for list_link in list_links:
        list_links[list_link]["url"] = "/reflexion/" + complement + "/" + list_link.replace(" ", "_").lower()

def list_files_in_path(path, ext):
    files = os.listdir(path)
    for file in files:
        if not file.lower().endswith('.' + ext.lower()):
            files.remove(file)
    return files


def index(request):
    link_activated(indicator_types, "")
    #link_activated(filenames, "")
    link_activated(actor_indicators, "")
    link_activated(network_indicators, "")
    
    #load template
    t = loader.get_template('reflexion1.html')
    c = Context({
        'title': 'IASNA Indicators: Welcome',
        'subtitle': "Welcome to IASNA Reflexion Board tool!",
        'indicator_type': indicator_types,
        'welcome': welcome,
        "options": indicator_types,
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
    })
    return HttpResponse(t.render(c))


def indicator_type(request, type):
    if type == "actor":
        return actor(request, type)
    elif type == "network":
        return network(request, type)
    elif type == "anytype":
        return anytype(request, type)
    else: return index(request)


def actor(request, type):
    
    filenames = {}
    fun1 = list_files_in_path(DIRS["CORE_RESULTS_ROOT"], 'xml')
    for f in fun1:
        filenames[f.replace(".xml", "")] = {"status": "inactive", "url": "/reflexion/" + type + "/" + f.replace(".xml", "").replace(" ", "_").lower()}
    
    link_activated(indicator_types, "Actor Indicator")
    link_activated(filenames, "")
    link_activated(actor_indicators, "")
    link_activated(network_indicators, "")
    #link_to_visit(filenames, type)
    
    #load template
    t = loader.get_template('reflexion1.html')
    c = Context({
        'title': 'IASNA Indicators: Actor Indicators for analysis',
        'subtitle': "Actor Indicators for analysis",
        'indicator_type': indicator_types,
        'filenames': filenames,
        'welcome': welcome,
        "options": filenames,
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
    })
    return HttpResponse(t.render(c))


def network(request, type):
    
    filenames = {}
    fun1 = list_files_in_path(DIRS["CORE_RESULTS_ROOT"], 'xml')
    for f in fun1:
        filenames[f.replace(".xml", "")] = {"status": "inactive", "url": "/reflexion/" + type + "/" + f.replace(".xml", "").replace(" ", "_").lower()}
    
    link_activated(indicator_types, "Network Indicator")
    link_activated(filenames, "")
    link_activated(actor_indicators, "")
    link_activated(network_indicators, "")
    #link_to_visit(filenames, type)
    
    #load template
    t = loader.get_template('reflexion1.html')
    c = Context({
        'title': 'IASNA Indicators: Network Indicators for analysis',
        'subtitle': "Network Indicators for analysis",
        'indicator_type': indicator_types,
        'filenames': filenames,
        'welcome': welcome,
        "options": filenames,
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
    })
    return HttpResponse(t.render(c))


def anytype(request, type):
    
    filenames = {}
    fun1 = list_files_in_path(DIRS["CORE_RESULTS_ROOT"], 'xml')
    for f in fun1:
        filenames[f.replace(".xml", "")] = {"status": "inactive", "url": "/reflexion/" + type + "/" + f.replace(".xml", "").replace(" ", "_").lower()}
    
    link_activated(indicator_types, "All type Indicator")
    link_activated(filenames, "")
    link_activated(actor_indicators, "")
    link_activated(network_indicators, "")
    
    #load template
    t = loader.get_template('reflexion1.html')
    c = Context({
        'title': 'IASNA Indicators: All type Indicators for analysis',
        'subtitle': "Any type Indicators for analysis",
        'indicator_type': indicator_types,
        'filenames': filenames,
        'welcome': welcome,
        "options": filenames,
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
    })
    return HttpResponse(t.render(c))


def activity_group(request, type, activity):
    
    filenames = {}
    fun1 = list_files_in_path(DIRS["CORE_RESULTS_ROOT"], 'xml')
    for f in fun1:
        filenames[f.replace(".xml", "")] = {"status": "inactive", "url": "/reflexion/" + type + "/" + f.replace(".xml", "").replace(" ", "_").lower()}
    
    if type == 'actor': link_activated(indicator_types, "Actor Indicator")
    elif type == 'network': link_activated(indicator_types, "Network Indicator")
    elif type == 'anytype': link_activated(indicator_types, "All type Indicator")
    link_activated(filenames, activity.upper())
    link_activated(actor_indicators, "")
    link_activated(network_indicators, "")
    link_to_visit(actor_indicators, type + "/" + activity)
    link_to_visit(network_indicators, type + "/" + activity)
    
    #load template
    t = loader.get_template('reflexion1.html')
    c = Context({})
    if type == "network":
        c = Context({
            'title': 'IASNA Indicators: Network Indicators for analysis',
            'subtitle': type.capitalize() + " Indicators for " + activity.upper(),
            'indicator_type': indicator_types,
            'filenames': filenames,
            'network_indicators': network_indicators,
            'type': type,
            'welcome': welcome,
            "options": network_indicators,
            'modules': modules,
            'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
        })
    elif type == "actor":
        c = Context({
            'title': 'IASNA Indicators: Actor Indicators for analysis',
            'subtitle': type.capitalize() + " Indicators for " + activity.upper(),
            'indicator_type': indicator_types,
            'filenames': filenames,
            'actor_indicators': actor_indicators,
            'type': type,
            'welcome': welcome,
            "options": actor_indicators,
            'modules': modules,
            'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
        })
    elif type == "anytype":
        c = Context({
            'title': 'IASNA Indicators: Any type Indicators for analysis',
            'subtitle': type.capitalize() + " Indicators for " + activity.upper(),
            'indicator_type': indicator_types,
            'filenames': filenames,
            'all_indicators': all_indicators,
            'type': type,
            'welcome': welcome,
            "options": all_indicators,
            'modules': modules,
            'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
        })
    return HttpResponse(t.render(c))


def indicator(request, type, activity, indicator):
    
    filenames = {}
    fun1 = list_files_in_path(DIRS["CORE_RESULTS_ROOT"], 'xml')
    for f in fun1:
        filenames[f.replace(".xml", "")] = {"status": "inactive", "url": "/reflexion/" + type + "/" + f.replace(".xml", "").replace(" ", "_").lower()}
    
    if type == 'actor': link_activated(indicator_types, "Actor Indicator")
    elif type == 'network': link_activated(indicator_types, "Network Indicator")
    elif type == 'anytype': link_activated(indicator_types, "All type Indicator")
    link_activated(filenames, activity.upper())
    link_activated(actor_indicators, indicator)
    link_activated(network_indicators, indicator)
    link_to_visit(actor_indicators, type + "/" + activity)
    link_to_visit(network_indicators, type + "/" + activity)
    
    if indicator.replace("_", " ").capitalize() in actor_indicators: type = 'actor'
    elif indicator.replace("_", " ").capitalize() in network_indicators: type = 'network'
    indicators = load_indicators_from_xml(type, activity, indicator)
    
    #load template
    t = loader.get_template('reflexion1.html')
    c = Context({
        'title': 'IASNA Indicators: Network Indicators for analysis',
        'subtitle': indicator.replace("_", " ").capitalize() + " for " + activity.upper(),
        'indicator_type': indicator_types,
        'type': type,
        'activity': activity,
        'filenames': filenames,
        'network_indicators': network_indicators,
        'actor_indicators': actor_indicators,
        'all_indicators': all_indicators,
        
        #'welcome': indicators,
        'indicators': indicators,
        
        'graph_url': DIRS["CORE_MEDIA_URL"] + activity.replace("_indicators", "") + '_all.jpg',
        "options": filenames,
        'modules': modules,
        'TEMPLATES_MEDIA_URL': TEMPLATES_MEDIA_URL,
    })
    return HttpResponse(t.render(c))


def load_indicators_from_xml(type, activity, indicator_name):
    
    pathfile = DIRS["CORE_RESULTS_ROOT"] + activity + '.xml'
    indicator_list = []
    indicator3 = []
    metrics = {}
    indicators = {}
    
    #return os.path.join(os.getcwd(), pathfile)
    
    # verifying if the file already exists and trying to open it
    if os.path.isfile(pathfile):
        try: datas = minidom.parse(pathfile)
        except XmlException.ExpatError: raise Exception, 'Error parseando el archivo %s' % activity + '_indicators.xml'
        except: raise Exception, "Error inesperado intentando datas = minidom.parse(%s)" % (activity + '_indicators.xml')

        for Activity in datas.getElementsByTagName("activity"):
                        
            indicator = {}
            indicator["session"] = str(int(float(Activity.getAttribute("session"))))
            try: indicators["datetime_ini"]
            except: indicators["datetime_ini"] = str(Activity.getAttribute("datetime_start"))
            indicators["datetime_end"] = str(Activity.getAttribute("datetime_finish"))
            
            # getting the network indicators for each activity
            if type == 'network':
                for network_indicator1 in Activity.getElementsByTagName("NetworkIndicator"):
                    if indicator_name:
                        if indicator_name == str(network_indicator1.getAttribute("id")).replace(" ", "_").lower():
                            #vector_network_indicators.append(network_indicator(network_indicator1.getAttribute("id"), network_indicator1.getAttribute("value")))
                            metrics = {}
                            indicators["name"] = str(network_indicator1.getAttribute("id"))
                            indicator["value"] = str(network_indicator1.getAttribute("value"))
                            for value in network_indicator1.getElementsByTagName("value"):
                                for value1 in value.childNodes:
                                    metrics[str(value.getAttribute("metric"))] = str(value1.data).strip()
                            indicator["metrics"] = metrics
                        #else: 
                        #    if "metrics" not in indicator and "value" not in indicator:
                        #        indicator = {}
                            
                #print indicator
                indicator3.append(indicator)
                
            else:
            # getting the actor indicators for each activity
                for actor_indicator1 in Activity.getElementsByTagName("ActorIndicator"):
                    if indicator_name:
                        
                        if indicator_name == str(actor_indicator1.getAttribute("id")).replace(" ", "_").lower():
                            
                            indicators["name"] = str(actor_indicator1.getAttribute("id"))
                            indicator_list = []
                            #indicator3 = []
                            
                            for actor in actor_indicator1.getElementsByTagName("node"):
                                metrics = {}
                                indicator = {}
                                
                                indicator["session"] = str(int(float(Activity.getAttribute("session"))))
                                indicator["actor"] = str(actor.getAttribute("id"))
                                indicator["value"] = str(actor.getAttribute("value"))
                                for value in actor.getElementsByTagName("value"):
                                    for value1 in value.childNodes:
                                        metrics[str(value.getAttribute("metric"))] = str(value1.data).strip()
                                indicator["metrics"] = metrics
                                indicator_list.append(indicator) #se adicionan los datos de los actores para el indicador
                                
                            #print indicator_list
                                
                            indicator3.append(indicator_list) #se adicionan los datos de los indicadores para cada actor en el indicador seleccionado
                        #else: 
                        #    if "metrics" not in indicator and "value" not in indicator:
                        #        indicator = {}

    
    #print indicator
    #print indicator3
    
    if type == "actor": indicators["indicator"] = indicator3
    elif type == "network": indicators["indicator"] = indicator3
    
    indicators["metrics_count"] = len(metrics)
    indicators["metrics_count_3"] = len(metrics) + 3
    indicators["metrics_count_2"] = len(metrics) + 2
    
    return indicators
